import getopt
import json
import os
import sys

import requests
import threadpool
from unipath import Path, FILES

os.system('chcp 65001')

api_key = 'e9cdf437c2c84b088c18008d6d225172'
domain = 'http://192.168.88.29:8096'
# 视频文件
video_type = ['.mp4', '.avi', '.rmvb', '.wmv', '.mov', '.mkv', '.flv', '.ts', '.webm', '.cus']


# 创建库
def create_lib(lib_name, lib_path):
    """
        创建库
    :param lib_name: 库的名字
    :param lib_path: 库的本地路径
    :return:
    """
    lib_data = {
        "LibraryOptions": {
            "EnableArchiveMediaFiles": False,
            "EnablePhotos": True,
            "EnableRealtimeMonitor": False,  # 实时监控文件，不要启动
            "ExtractChapterImagesDuringLibraryScan": False,
            "EnableChapterImageExtraction": False,
            "SaveLocalThumbnailSets": False,
            "ThumbnailImagesIntervalSeconds": "10",
            "DownloadImagesInAdvance": False,
            "EnableInternetProviders": False,
            "ImportMissingEpisodes": False,
            "SaveLocalMetadata": False,
            "EnableAutomaticSeriesGrouping": True,  # 启用自动系列分组
            "PreferredMetadataLanguage": "",
            "PreferredImageLanguage": "",
            "MetadataCountryCode": "",
            "SeasonZeroDisplayName": "Specials",
            "AutomaticRefreshIntervalDays": 0,
            "EnableEmbeddedTitles": False,
            "SkipSubtitlesIfEmbeddedSubtitlesPresent": False,
            "SkipSubtitlesIfAudioTrackMatches": False,
            "SaveSubtitlesWithMedia": False,
            "RequirePerfectSubtitleMatch": False,
            "EnableAudioResume": False,
            "MinResumePct": "5",
            "MaxResumePct": "90",
            "MinResumeDurationSeconds": "180",
            "MetadataSavers": [

            ],
            "TypeOptions": [
                {
                    "Type": "Movie",
                    "MetadataFetchers": [

                    ],
                    "MetadataFetcherOrder": [
                        "TheMovieDb",
                        "The Open Movie Database"
                    ],
                    "ImageFetchers": [
                        "TheMovieDb",
                        "FanArt",
                        "Screen Grabber"
                    ],
                    "ImageFetcherOrder": [
                        "TheMovieDb",
                        "FanArt",
                        "The Open Movie Database",
                        "Screen Grabber"
                    ]
                }
            ],
            "LocalMetadataReaderOrder": [
                "Nfo"
            ],
            "SubtitleDownloadLanguages": [

            ],
            "DisabledSubtitleFetchers": [
                "Open Subtitles"
            ],
            "SubtitleFetcherOrder": [
                "Open Subtitles"
            ],
            "PathInfos": [
                {
                    "Path": lib_path
                }
            ],
            "ContentType": "movies"
        }
    }
    url = '{0}/emby/Library/VirtualFolders'.format(domain)
    headers = {
        'Accept': '*/*',
        "Content-Type": "application/json;charset=UTF-8",
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.75 Safari/537.36',
    }
    # 参数
    params = {
        'api_key': api_key,
        'collectionType': 'movies',
        'refreshLibrary': 'true',
        'name': lib_name
    }
    # 请求数据
    response = requests.post(headers=headers, url=url, params=params, data=json.dumps(lib_data))
    print("创建视频完成")
    return response.text


# 目录路径映射
def mapping_dir_path(local_path, gd_path):
    local_path = Path(local_path)
    gd_path = Path(gd_path)
    if not Path(gd_path).exists():
        print("[+] 无效路径：" + gd_path)
        return
    local_path.rename(Path(local_path.parent, local_path.stem + '_original'))
    # 执行命令
    cmd = 'mklink /D {0} {1}'.format(local_path, gd_path)
    if (os.system(cmd)) == 0:
        print("执行完成")


# ---------------------------- 文件路劲映射
def mapping_file_path(param_local_path, param_gd_path):
    param_local_path = Path(param_local_path)
    param_gd_path = Path(param_gd_path)

    if not param_local_path.exists():
        print("[E] 本地路径【无效】：{0}".format(param_local_path))
        return

    if not param_gd_path.exists():
        print("[e] 网盘路径【无效】：{0}".format(param_gd_path))
        return
    # gd文件路径
    mapping_local_gd_file_path = []
    no_path = []
    for item_path in param_local_path.walk(filter=FILES):
        print('[+] {0}'.format(item_path))
        # 不是视频文件，跳过
        if not item_path.ext.lower() in video_type:
            continue
        # 挑出自定义文件
        if item_path.ext.lower() in ['.cus']:
            continue
        mapping_local_gd_file_path.append(((item_path, Path(item_path.replace(param_local_path, param_gd_path))), None))

    pool = threadpool.ThreadPool(15)

    make_request = threadpool.makeRequests(thread_mapping_file_path, mapping_local_gd_file_path)
    [pool.putRequest(req) for req in make_request]
    pool.wait()
    print("********************************")
    print("******** 无效的路径")
    print("********************************")
    for item_path in no_path:
        print('[!] {0}'.format(item_path))

    print('[!] 映射完毕')


# 映射路径
def thread_mapping_file_path(param_source_path, param_target_path):
    param_source_path = Path(param_source_path)
    param_target_path = Path(param_target_path)
    print("[S] {0}".format(param_source_path))
    print("[T] {0}".format(param_target_path))
    if not param_source_path.exists():
        print("[!] 无效路径：{0}".format(param_source_path))
        return

    if param_source_path.islink():
        print("[R] 已经映射：{0}".format(param_source_path))
        return

    # param_source_path.remove()
    param_source_path.rename(Path(param_source_path + ".cus"))
    param_source_path.make_relative_link_to(param_target_path)
    print("[+] 映射完成 ：{0}".format(param_source_path))
    # # 执行命令
    # os.system('MKLINK {0} {1}'.format(target_file_path, item_path))


# ---------------------------- 还原映射
def undo_mapping_file_path(local_path):
    local_path = Path(local_path)
    dirs = local_path.listdir()
    # 线程池
    pool = threadpool.ThreadPool(15)
    make_request = threadpool.makeRequests(thread_undo_mapping_file_path, dirs)
    [pool.putRequest(req) for req in make_request]
    pool.wait()


def thread_undo_mapping_file_path(param_dir_path):
    param_dir_path = Path(param_dir_path)
    if not Path(param_dir_path).exists():
        print("[+] 无效路径：" + param_dir_path)
        return

    cus_file_path_list = []
    for root, dirs, files in os.walk(param_dir_path):
        for item_file in files:
            source_file = Path(root, item_file)
            # 不是视频文件，跳过
            if not os.path.splitext(item_file)[1].lower() in video_type:
                continue

            # 挑出自定义文件
            if os.path.splitext(item_file)[1].lower() in ['.cus']:
                cus_file_path_list.append(source_file)

            # 如果是软连接，就删除
            if source_file.islink():
                source_file.remove()
                print('[-] {0}'.format(source_file))
            # 创新创建文件
            # file_stream = open(source_file, "wb", buffering=0)
            # file_stream.close()

    # 回溯自定义文件
    for cus_file_path in cus_file_path_list:
        cus_file_path.rename(Path(cus_file_path.parent, cus_file_path.stem))
        print('[+] {0}'.format(cus_file_path))


# 获取所有的库
# url = '{0}/emby/Library/VirtualFolders'.format(domain)
# python emby_lib-tools.py -n create_lib -l C:\data\meta-data\影视合集\CMCT-720P
# python emby_lib-tools.py -n mapping_file_path -l E:\临时文件\数据工厂\temp -g Y:\2.1、影视合集\影视资源\情色电影
# python emby_lib-tools.py -n undo_mapping_file_path -l E:\临时文件\数据工厂\temp
if __name__ == '__main__':
    if len(sys.argv) == 1:
        sys.exit()
    try:
        par_local_path = ""
        par_gd_path = ""
        par_func_name = ''
        opts, args = getopt.getopt(sys.argv[1:], "l:g:n:", ["help", "output="])
        for n, v in opts:
            if n in ('-g', '--gd_dir_path'):
                par_gd_path = v
            elif n in ('-l', '--local_dir_path'):
                par_local_path = v
            elif n in ('-n', '--fun_name'):
                par_func_name = v

        if par_func_name == 'create_lib':
            if len(par_local_path) == 0:
                print("[!] 本地路径不存在")
                sys.exit()
            create_lib('欧美剧', par_local_path)
        elif par_func_name == 'mapping_file_path':
            if len(par_local_path) == 0:
                print("[!] 本地路径不存在")
                sys.exit()
            if len(par_gd_path) == 0:
                print("[!] 网盘路径不存在")
                sys.exit()
            mapping_file_path(param_local_path=par_local_path, param_gd_path=par_gd_path)
        elif par_func_name == 'undo_mapping_file_path':
            if len(par_local_path) == 0:
                print("[!] 本地路径不存在")
                sys.exit()
            undo_mapping_file_path(local_path=par_local_path)

    except getopt.GetoptError:
        print("Argv error,please input")
